<script setup>
import {ref, computed} from 'vue'
import ComAffix from "@/components/ComAffix.vue";
import {ElMessage} from 'element-plus'
import router from '@/router/index.js'

const route = computed(() => router.currentRoute.value);
import {useUserInfoStore, useUserStore} from "@/stores/index.js";
import {follow, postCollect, postLike} from '@/utiles/userInfo.js'
import {checkLogin} from "@/utiles/route.js";
import {getPostDetailService} from "@/api/post.js";
import {
  addPostCollectByCategory,
  addPostViewsService, createCollectCategory,
  getCollectCategories
} from "@/api/postInfo.js";
import {
  addComment,
  addCommentLike,
  delCommentLike,
  getCommentLikes,
  getCommentsByPostId
} from "@/api/comment.js";
import V3Emoji from 'vue3-emoji'
import 'vue3-emoji/dist/style.css'
import useAutoHide from "@/utiles/useAutoHide.js";
import {Plus} from "@element-plus/icons-vue";

const userInfoStore = useUserInfoStore()
const userStore = useUserStore();
// 通过props接收参数
const props = defineProps({
  id: {
    type: String,
    required: true
  }
})
console.log(props.id + " " + route.value.query.authorId)

// 模拟数据
const author = ref({})


const post = ref({
  id: props.id,
  title: '',
  content: '',
  likeCount: 0,
  commentCount: 0,
  collectCount: 0,
  tags: []
})
const getPost = async () => {
  const res = await getPostDetailService(props.id);
  post.value = res.data.data
  author.value = res.data.data.author
}
getPost()
addPostViewsService(props.id)


// 评论数据
const commentContent = ref('')
const comments = ref([]) // 保持你的现有数据
const getComments = async () => {
  const postId = post.value.id;
  const res = await getCommentsByPostId(postId)
  comments.value = res.data.data
}
getComments()

const handleFollow = (sign) => {
  follow(Number(author.value.id), sign)
}

const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'


//用户点开帖子页面，从后端取出帖子用户关联的评论_点赞数据，
const userCommentLikes = ref([])

const getUserCommentLikes = async () => {
  const res = await getCommentLikes(props.id);
  userCommentLikes.value = res.data.data
}
getUserCommentLikes()


// 点赞处理
const handleCommentLike = (comment, sign) => {
  if (!checkLogin())
    return;
  if (sign === 0) {
    addCommentLike(comment.id)
    comment.likes = (comment.likes || 0) + 1
    userCommentLikes.value.push(comment.id)

  } else if (sign === 1) {
    delCommentLike(comment.id)
    comment.likes = (comment.likes || 0) - 1
    userCommentLikes.value = userCommentLikes.value.filter(item => item !== comment.id)
  }
}

// 回复相关状态
const activeReplyId = ref(null)
const replyContent = ref('')

// 获取一级评论
const sortedComments = computed(() => {
  return comments.value
    .filter(c => c.type === 0)
    .sort((a, b) => new Date(a.createTime) - new Date(b.createTime))
})

// 获取子评论
const getChildComments = (parentId) => {
  return comments.value
    .filter(c => c.parentId === parentId)
    .sort((a, b) => new Date(a.createTime) - new Date(b.createTime))
}

// 时间格式化
const formatTime = (timeStr) => {

  const date = new Date(timeStr)
  const pad = n => n.toString().padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}


//帖子评论收藏
const [showCollectionList, setShowCollectionList] = useAutoHide(false, 3000)

const collectCategories = ref([])
const favoritesCard = ref(false)
const showCreateDialog = ref(false)
const newFavorite = ref({name: '', describe: ''})

const handlePostLike = (id, sign) => {
  postLike(Number(id), sign, post.value)
}
const handlePostCollect = (id, sign) => {
  postCollect(Number(id), sign, post.value)
  if (sign === 0) {
    showCollectionList.value = true
    setShowCollectionList(true)
  }
}
const getFavorites = async () => {
  const res = await getCollectCategories()
  collectCategories.value = res.data.data
}
getFavorites()

const toggleCollect = async (id) => {
  const param = {categoryId: id, postId: props.id, authorId: author.value.id}
  await addPostCollectByCategory(param)
  favoritesCard.value = false
  await getFavorites()
}
const createFavorite = async () => {
  try {
    await createCollectCategory(newFavorite.value)
    showCreateDialog.value = false
    await getFavorites()
    newFavorite.value = {name: '', describe: ''}
    ElMessage.success('创建成功')
  } catch (err) {
    console.error('创建失败' + err)
  }
}

// 切换回复框
const toggleReplyBox = (commentId) => {
  if (activeReplyId.value === commentId) {
    activeReplyId.value = null
    replyContent.value = ''
  } else {
    activeReplyId.value = commentId
  }
}
const clickEmoji = (val) => {
  replyContent.value += val;
}
//1级2级评论发布
const submitReply = async (parentComment, type, parentId) => {
  post.value.commentCount++;
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  if (!checkLogin())
    return;

  const newComment = {
    postId: post.value.id,
    userId: userStore.user.id, // 替换为当前用户ID
    userName: userStore.user.nickname, // 替换为当前用户名
    userAvatar: userStore.user.avatar,
    authorId: route.value.query.authorId,
    content: replyContent.value.replace(/^@\S+\s/, ''),
    type: type,
    parentId: parentId,
    replyUserId: parentComment.userId,
    replyUserName: parentComment.userName,
    replyCommentId: parentComment.id
  }
  console.log("newComment: " + newComment.authorId)
  await addComment(newComment);
  await getComments();
  cancelReply()
  await getPost()
}
// 取消回复
const cancelReply = () => {
  activeReplyId.value = null
  replyContent.value = ''
}
//跳转标签页
const viewTag = (tagName) => {
  router.push({
    name: 'SearchTag',
    query: {
      tagName: tagName
    }
  })
}
//0级评论发布
const publishComment = async () => {
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  if (!checkLogin())
    return;
  const newComment = {
    postId: post.value.id,
    userId: userStore.user.id, // 替换为当前用户ID
    userName: userStore.user.nickname, // 替换为当前用户名
    userAvatar: userStore.user.avatar,
    authorId: route.value.query.authorId,
    content: commentContent.value,
    type: 0,
    parentId: null,
    replyUserId: route.value.query.authorId,
    replyUserName: route.value.query.authorName,
    replyCommentId: null
  }
  console.log("newComment: " + newComment.authorId)

  commentContent.value = ''
  await addComment(newComment);
  await getComments()
  await getPost()
}
</script>

<template>
  <div class="main">
    <el-affix :offset="0">
      <ComAffix></ComAffix>
    </el-affix>
    <!-- 左侧作者信息栏 -->
    <div class="author-sidebar">
      <div class="author-info">
        <span class="author-avatar">
          <el-avatar :size="80" :src="author.avatar"/>
          <span class="author-name"><router-link
            :to="{ name: 'OtherUser', query: { userId: author.id} }">{{
              author.nickname
            }}</router-link></span>
        </span>
        <p class="author-introduced">{{ author.introduced }}</p>
      </div>
      <div class="author-button" v-show="author.id!==userStore.user.id">
        <span class="privateMgs">私信</span>
        <span class="followed" v-if="userInfoStore.follow.includes(Number(author.id))"
              @click="handleFollow(1)">已关注</span>
        <span class="follow" v-else @click="handleFollow(0)">关注</span>

      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 帖子标题 -->
      <h1 class="post-title">{{ post.title }}</h1>

      <!-- 帖子内容 -->
      <div class="post-content">
        <div v-html="post.content" class="post"></div>
      </div>

      <div class="tags">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-tubiao_biaoqian"></use>
        </svg>
        <span v-for="(tag, tagIndex) in post.tags" :key="tagIndex" class="tag"
              @click="viewTag(tag)">
                   {{ tag }}
        </span>
      </div>

      <div class="comment">
        <span class="comment-count">评论({{ post.commentCount }})</span>
        <div
          v-for="comment in sortedComments"
          :key="comment.id"
          class="comment-item"
        >
          <!-- 评论主体 -->
          <div class="comment-main" :class="`level-${comment.type}`">
            <!-- 用户信息 -->
            <div class="user-info">
              <el-avatar :size="36" :src="comment.userAvatar || defaultAvatar"/>
              <div class="meta">
                <div class="name-row">
                  <span class="user-name" v-if="Number(comment.userId) !== Number(author.id)">{{
                      comment.userName
                    }}</span>
                  <span class="author" v-else>作者</span>

                  <span v-if="comment.type === 3" class="reply-hint">
                  回复 @{{ comment.replyUserName }}
                </span>
                </div>
              </div>
            </div>

            <!-- 评论内容 -->
            <div class="content">{{ comment.content }}</div>

            <!-- 操作按钮 -->
            <div class="actions">
              <div class="time">{{ formatTime(comment.createTime) }}</div>
              <span class="like_icon">
               <svg class="icon" aria-hidden="true" @click="handleCommentLike(comment,0)"
                    v-if="!userCommentLikes.includes(comment.id)">
                  <use xlink:href="#icon-dianzan"></use>
              </svg>
              <svg class="icon" aria-hidden="true" @click="handleCommentLike(comment,1)" v-else>
                  <use xlink:href="#icon-dianzanshoucang"></use>
              </svg>
            </span>
              <span class="like">{{ comment.likes }}</span>

              <span
                class="reply-action"
                @click="toggleReplyBox(comment.id)"
              >
              {{ activeReplyId === comment.id ? '取消回复' : '回复' }}
            </span>
            </div>

            <!-- 回复编辑器 -->
            <div v-if="activeReplyId === comment.id" class="reply-editor">
              <el-input
                v-model="replyContent"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                :placeholder="`回复 @${comment.userName}`"
                :maxlength="500"
              />
              <div class="editor-actions">
              <span
                class="reply-button"
                @click="submitReply(comment,1,comment.id)"
              >
                发送
              </span>
                <span class="emoji">
                    <V3Emoji
                      @click-emoji="clickEmoji"
                      :options-name="customIcon"
                      :recent="true"
                      :custom-size="customSize"
                    />
                  </span>
              </div>
            </div>
          </div>

          <!-- 子评论 -->
          <div
            v-for="child in getChildComments(comment.id)"
            :key="child.id"
            class="child-comments"
          >
            <div class="comment-main" :class="`level-${child.type}`">
              <!-- 重复相同的评论结构 -->
              <!-- 用户信息 -->
              <div class="user-info">
                <el-avatar :size="32" :src="child.userAvatar || defaultAvatar"/>
                <div class="meta">
                  <div class="name-row">
                    <span class="user-name" v-if="Number(child.userId) !== Number(author.id)">{{
                        child.userName
                      }}</span>
                    <span class="author" v-else>作者</span>
                    <span v-if="child.type === 2" class="reply-hint">
                    <span class="reply">回复</span> <span class="reply-name">@{{
                        child.replyUserName
                      }}</span>
                  </span>
                  </div>
                </div>
              </div>

              <!-- 评论内容 -->
              <div class="content">{{ child.content }}</div>

              <!-- 操作按钮 -->
              <div class="actions">
                <div class="time">{{ formatTime(child.createTime) }}</div>
                <span class="like_icon">
               <svg class="icon" aria-hidden="true" @click="handleCommentLike(child,0)"
                    v-if="!userCommentLikes.includes(child.id)">
                  <use xlink:href="#icon-dianzan"></use>
              </svg>
              <svg class="icon" aria-hidden="true" @click="handleCommentLike(child,1)" v-else>
                  <use xlink:href="#icon-dianzanshoucang"></use>
              </svg>
            </span>
                <span class="like">{{ child.likes }}</span>
                <span
                  @click="toggleReplyBox(child.id)"
                  class="reply-action"
                >
                {{ activeReplyId === child.id ? '取消回复' : '回复' }}
              </span>
              </div>

              <!-- 回复编辑器 -->
              <div v-if="activeReplyId === child.id" class="reply-editor">
                <el-input
                  v-model="replyContent"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"
                  :placeholder="`回复 @${child.userName}`"
                  :maxlength="500"
                  autofocus
                />
                <div class="editor-actions">
                <span
                  @click="submitReply(child,2,comment.id)"
                  class="reply-button"
                >
                  发送
                </span>
                  <span class="emoji">
                    <V3Emoji
                      @click-emoji="clickEmoji"
                      :options-name="customIcon"
                      :recent="true"
                      :custom-size="customSize"
                    />
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="favoritesCard"
      :show-close="false"
      width="500px"
      custom-class="collect-dialog"
    >
      <!-- 自定义头部 -->
      <template #header>
        <div class="dialog-header">
          <h3 class="dialog-title">添加收藏夹</h3>
        </div>
      </template>

      <!-- 内容区域 -->
      <div class="dialog-content">
        <!-- 创建收藏夹 -->
        <div class="create-area" @click="showCreateDialog = true" style="cursor: pointer">
          <div class="create-left">
            <el-icon class="add-icon">
              <Plus/>
            </el-icon>
            <span>创建收藏夹</span>
          </div>
        </div>

        <!-- 收藏夹列表 -->
        <div class="collect-list">
          <div
            v-for="item in collectCategories"
            :key="item.id"
            class="collect-item"
          >
            <div class="item-info">
              <h4 class="item-title">{{ item.name }}</h4>
              <span class="collect-btn"
                    @click="toggleCollect(item.id)">
              收藏
            </span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 创建收藏夹对话框 -->
    <el-dialog v-model="showCreateDialog" title="新建收藏夹">
      <el-form :model="newFavorite">
        <el-form-item label="名称">
          <el-input v-model="newFavorite.name"/>
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="newFavorite.describe" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createFavorite">创建</el-button>
      </template>
    </el-dialog>
    <!-- 底部操作栏 -->
    <div class="action-footer">
      <div class="comment">
        <el-input
          v-model="commentContent"
          :autosize="{ minRows: 1, maxRows: 3 }"
          type="textarea"
          placeholder="评论"
          :maxlength="500"
          size="large"
          class="comment-count"
        />
        <span class="publish" @click="publishComment()">发布</span>
      </div>
      <div class="show">
        <div
          v-show="showCollectionList"
          class="favorites-card"
        >
          <span class="collect-success">收藏成功</span>
          <span class="add-favorite" @click="favoritesCard=true"
                style="cursor: pointer">加入收藏夹</span>
        </div>


        <span class="like">
              <svg class="icon" aria-hidden="true" @click="handlePostLike(post.id,0)"
                   v-if="!userInfoStore.postLike.includes(Number(post.id))">
                  <use xlink:href="#icon-dianzan_selected2"></use>
              </svg>
              <svg class="icon" aria-hidden="true" @click="handlePostLike(post.id,1)" v-else>
                  <use xlink:href="#icon-yizan1"></use>
              </svg>
              <span class="num">{{ post.likeCount }}</span>
        </span>
        <span class="collection">
              <svg class="icon" aria-hidden="true" @click="handlePostCollect(post.id,0)"
                   v-if="!userInfoStore.postCollect.includes(Number(post.id))">
                  <use xlink:href="#icon-weishoucang"></use>
              </svg>
              <svg class="icon" aria-hidden="true" @click="handlePostCollect(post.id,1)" v-else>
                  <use xlink:href="#icon-a-shoucang-yishoucang"></use>
              </svg>
              <span class="num">{{ post.collectCount }}</span>
        </span>
      </div>
    </div>
  </div>
</template>


<style scoped>
.main {
  background-color: #f6f3f3;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #EBEEF5;

  .dialog-title {
    margin: 0;
    font-size: 16px;
    color: #303133;
  }

  .close-btn {
    cursor: pointer;
    color: #909399;
    transition: color 0.3s;
  }

  .close-btn:hover {
    color: #606266;
  }

  .create-area {
    padding: 12px 0;
    cursor: pointer;
    transition: background 0.3s;
  }

  .create-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .add-icon {
    color: #F56C6C;
    font-size: 20px;
  }

  .collect-list {
    margin-top: 16px;
  }

  .list-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
  }

  .list-title {
    font-size: 14px;
    color: #303133;
  }

  .recent-tag {
    color: #F56C6C;
    font-size: 12px;
  }

  .collect-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #F5F7FA;
  }

  .item-title {
    margin: 0;
    font-size: 14px;
    color: #303133;
  }

  .item-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 4px;
  }

  .count {
    font-size: 12px;
    color: #909399;
  }

  .collect-btn {
    width: 80px;
    transition: all 0.3s;
  }

  /* 调整Element组件样式 */

  :deep(.el-dialog__header) {
    padding: 0 !important;
    margin: 0 !important;
  }

  :deep(.el-dialog__body) {
    padding: 16px 20px !important;
  }
}


.author-sidebar {
  width: 200px;
  position: fixed;
  left: 40px;
  top: 80px;
  background: #fff;
  padding: 30px;

  .author-info {
    margin-bottom: 20px;

    .author-avatar {
      position: relative;

      .author-name {
        width: 120px;
        position: absolute;
        left: 100px;
        margin: 10px 0;
        font-size: 25px;
        font-family: 'serif', '楷体';
      }

    }

    .author-introduced {
      font-size: 13px;
      font-family: 'serif', '微软雅黑';
      color: #7a7a7a;
      margin-top: 20px;
    }
  }

  .author-button {
    .privateMgs {
      display: inline-block;
      width: 55px;
      padding-left: 30px;
      height: 30px;
      line-height: 30px;
      border-radius: 20px;
      border: 1px solid #cac9c9;
      font-size: 14px;
      cursor: pointer;
    }

    .follow {
      display: inline-block;
      width: 55px;
      padding-left: 30px;
      height: 30px;
      line-height: 30px;
      border-radius: 20px;
      border: 1px solid #cac9c9;
      font-size: 14px;
      margin-left: 20px;
      cursor: pointer;
    }

    .followed {
      display: inline-block;
      width: 60px;
      padding-left: 20px;
      height: 30px;
      line-height: 30px;
      border-radius: 20px;
      border: 1px solid #cac9c9;
      font-size: 14px;
      margin-left: 20px;
      background-color: #3b789d;
      color: white;
      cursor: pointer;
    }
  }

}

.main-content {
  margin-left: 300px;
  margin-right: 200px;
  max-width: 800px;
  min-height: 500px;
  background-color: #ffffff;
  margin-top: 11px;
  padding: 40px 40px 100px;

  .post-title {
    font-size: 24px;
    color: #333;
    text-align: center;
    font-family: 'serif', '黑体';
  }

  .post-content {
    line-height: 1.8;
    font-size: 16px;
    color: #666;
    font-family: 'serif', '微软雅黑';
  }

  :deep(.post) img {
    width: 500px;
  }

  .tags {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    padding: 20px 0;
    border-bottom: 1px solid #e6e5e5;

    .icon {
      height: 20px;
      width: 20px;
      margin-top: 2px;
      margin-right: 5px;
    }

    .tag {
      padding: 2px 5px;
      height: 20px;
      font-size: 15px;
      color: #838383;
      font-family: '华文楷体', serif;

    }

    .tag:hover {
      cursor: pointer;
      background-color: #a5a4a4;
      color: #f6f5f5;
    }

  }

  .comment {
    width: 580px;

    .comment-count {
      display: inline-block;
      margin-left: 15px;
      margin-top: 20px;
      color: #878787;
      font-size: 14px;
      font-weight: 600;
    }

    .comment-main {
      margin: 10px 0;
      padding-left: 10px;
    }

    .child-comments {
      margin-left: 40px;
      padding-left: 10px;
    }

    .comment-item {
      padding: 5px;
      border-radius: 6px;
      transition: background 0.2s;
    }

    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      margin-right: 10px;

      .user-avatar {
        flex-shrink: 0;
      }

      .meta {
        margin-left: 12px;
        line-height: 1.4;
      }

      .name-row {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .user-name {
        font-weight: 500;
        font-size: 13px;
        color: #4e4e4e;
        font-family: 'serif', '微软雅黑';
        margin-right: 5px;
      }

      .reply-hint {
        font-size: 15px;

        .reply {
          font-family: 'serif', '黑体';
          font-weight: 550;
        }

        .reply-name {
          color: #01aaf1;
        }
      }


    }

    .content {
      font-size: 14px;
      line-height: 1.6;
      font-family: 'serif', '微软雅黑';
      white-space: pre-wrap;
      word-break: break-word;
    }

    .actions {
      margin-top: 5px;
      display: flex;
      align-items: center;
      gap: 16px;

      .time {
        font-size: 12px;
        color: #909399;
      }

      :deep(.el-button) {
        padding: 0;
        height: auto;
      }

      .like {
        margin-left: -13px;
        margin-bottom: 1px;
        color: #646464;
        font-size: 14px;
        cursor: pointer;
      }

      .icon {
        width: 20px;
        height: 20px;
        color: #7a7a7a;
        cursor: pointer;
      }
    }

    .reply-button {
      height: 25px;
      width: 37px;
      display: inline-block;
      line-height: 25px;
      padding: 5px 15px;
      background-color: #7fd6f5;
      color: #fff;
      border-radius: 8px;
      cursor: pointer;
    }

    .reply-action {
      color: #909399;
      font-size: 14px;
      cursor: pointer;
      margin-bottom: 3px;
    }

    .emoji {
      float: right;
    }

  }
}

.action-footer {
  position: fixed;
  bottom: 0;
  left: 309px;
  right: 209px;
  background: #fff;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);

  .comment {
    float: left;
    position: relative;

    .comment-count {
      width: 420px;
    }

    .publish {
      height: 22px;
      width: 35px;
      display: inline-block;
      line-height: 22px;
      padding: 5px 15px;
      background-color: #7fd6f5;
      color: #fff;
      border-radius: 8px;
      cursor: pointer;
    }
  }

  .show {
    position: absolute;
    bottom: 18px;
    left: 520px;

    .favorites-card {
      height: 50px;
      width: 250px;
      background-color: white;
      border: 1px solid #ebeef5;
      border-radius: 15px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
      align-content: center;
      position: fixed;
      bottom: 60px;
      right: 208px;

      .collect-success {
        margin-left: 20px;
        font-size: 18px;
        font-weight: bold;
      }

      .add-favorite {
        margin-left: 55px;
        color: #7a7a7a;
      }

    }

    .icon {
      height: 20px;
      width: 20px;
      cursor: pointer;
    }

    .num {
      font-size: 14px;
      margin-left: 5px;
    }

    .collection {
      margin-left: 10px;
    }
  }
}

a {
  text-decoration: none;
  cursor: pointer;
  color: black;
}

.author {
  display: inline-block;
  width: 40px;
  border-radius: 8px;
  height: 20px;
  background-color: #fbd3da;
  opacity: 0.8;
  text-align: center;
  color: #ed0b38;
  font-size: 14px;
}


</style>
